<template>
  <div>
    <cfg-table ref="table" :columns="columns" :data="data" :loading="loading" :config="config"
      :pageSizeOpts="pageSizeOpts" :pageNavigation="pageNavigation" :queryFormItem="queryFormItem"
      :collapseFormItem="collapseFormItem" :additionalAction="additionalAction" @loadPage="loadPage"
      @handleCreate="handleCreate" @handleDetail="handleDetail" @handleEdit="handleEdit" @handleDelete="handleDelete"
      @handleDeleteMultiple="handleDeleteMultiple" @handleSearch="handleSearch" @handleReset="handleReset"></cfg-table>
    <CfgStatisticsModelNewAddModal v-bind="addNewPanel" @submit="handleNewAddSubmit" />
    <CfgStatisticsModelEditModal v-bind="editPanel" @submit="handleEditSubmit" />
    <CfgStatisticsModelReadModal v-bind="readPanel" />
    <formulaEditor :drawer="hierDrawer" :modelType="modelType" :value="hierData" @submit="submitHier" />
  </div>
</template>

<script>
import formulaEditor from "../../formulaEditor/index.vue"

export default {
  name: "statisticsModel",
  components: { formulaEditor },
  data() {
    return {
      classObject: null,
      collectionObject: null,
      addNewPanel: {
        width: 1024,
        zIndex: 100,
        titleStyle: {},
        drawer: {
          show: false
        }
      },
      editPanel: {
        width: 1024,
        zIndex: 100,
        titleStyle: {},
        drawer: {
          show: false
        },
        data: {}
      },
      readPanel: {
        width: 1024,
        zIndex: 100,
        titleStyle: {},
        drawer: {
          show: false
        },
        data: {}
      },
      record: {},
      modelType: '',
      hierData: {
        "saveToField": "sf_result",
        "expression": "sum(<#res0.df_count1#>)+sum(<#res0.df_count2#>)",
        "param": {},
        "params": [
          {
            "result": {
              "path": ["df_count1", "df_count2", "df_price"],
              "var": "res0",
              "type": "list"
            },
            "pointer": { "className": "test_ent", "type": "entity" },
            "condition": "",
            "action": "query",
            "model": "entity"
          }
        ]
      },
      hierDrawer: {
        show: false,
      },
      loading: false,
      config: {
        search: true,
        addButton: true,
        batchDeleteButton: true,
        downloadIcon: false,
        uploadIcon: false,
        uploadUrl: '/',
        tableSizeIcon: true,
        fullscreenIcon: true,
        refreshIcon: true,
        columnSettingIcon: true,
        action: true,
        additionalAction: true
      },
      pageSizeOpts: [10, 30, 50, 100],
      pageNavigation: { total: 0, pageSize: 10, pageNumber: 1 }
    }
  },
  props: {

  },
  computed: {
    columns() {
      return [
        {
          key: 'type',
          title: {
            'zh-CN': '所属类型',
            'en-US': 'type'
          }[this.G_Locale],
          minWidth: 100,
          align: 'center',
          show: true
        },
        {
          key: 'className',
          title: {
            'zh-CN': '模型类名',
            'en-US': 'class name'
          }[this.G_Locale],
          minWidth: 100,
          align: 'center',
          show: true
        },
        /* {
          key: 'version',
          title: {
            'zh-CN': '版本号',
            'en-US': 'version'
          }[this.G_Locale],
          minWidth: 100,
          align: 'center',
          show: true,
        },
        {
          key: 'published',
          title: {
            'zh-CN': '是否发布',
            'en-US': 'published'
          }[this.G_Locale],
          minWidth: 100,
          align: 'center',
          show: true
        }, */
        {
          key: 'createTime',
          title: {
            'zh-CN': '创建时间',
            'en-US': 'create time'
          }[this.G_Locale],
          width: 112,
          align: 'center',
          show: true,
        },
        {
          key: 'updateTime',
          title: {
            'zh-CN': '更新时间',
            'en-US': 'update time'
          }[this.G_Locale],
          width: 112,
          align: 'center',
          show: true,
        },
      ]
    },
    queryFormItem() {
      return [
        {
          key: 'type',
          title: {
            'zh-CN': '所属类型',
            'en-US': 'type'
          }[this.G_Locale],
          config: {
            type: 'text'
          }
        },
        {
          key: 'className',
          title: {
            'zh-CN': '模型类名',
            'en-US': 'class name'
          }[this.G_Locale],
          config: {
            type: 'text'
          }
        },
      ]
    },
    collapseFormItem() {
      return [
        {
          key: 'type',
          title: {
            'zh-CN': '所属类型',
            'en-US': 'type'
          }[this.G_Locale],
          config: {
            type: 'text'
          }
        },
        {
          key: 'className',
          title: {
            'zh-CN': '模型类名',
            'en-US': 'class name'
          }[this.G_Locale],
          config: {
            type: 'text'
          }
        },
      ]
    },
    additionalAction() {
      return {
        key: 'additionalAction',
        title: { 'zh-CN': '附加操作', 'en-US': 'addition action' }[this.G_Locale],
        slot: 'additionalAction',
        width: 100,
        fixed: 'right',
        align: 'center',
        show: true,
        buttons: [
          { title: { 'zh-CN': '公式', 'en-US': 'formula' }[this.G_Locale], color: 'green', event: (row, index) => this.hierDesign(row, index) },
        ]
      }
    },
    data() {
      if (!!this.collectionObject) {
        return this.collectionObject.records;
      } else {
        return [];
      }
    }
  },
  beforeMount() {
    this.collectionObject = this.$modelObject.create('statisticsModelCollection');
    this.classObject = this.$modelObject.create('statisticsModel')
    this.model = this.$modelObject.getClass('formula');
    // this.hierData = this.model.tpl();
    this.loadPage(this.pageNavigation, null)
  },
  mounted() {
    // this.$api.StatisticsInstance.statistics({id: 4})
  },
  methods: {
    loadPage(pageNavigation, filter) {
      let newFilter = "";
      if (this.tools.isReal(filter)) {
        newFilter = this.collectionObject.util.getFilter(filter);
      }
      this.loading = true;
      this.collectionObject.queryInfoByPage(pageNavigation.pageNumber, pageNavigation.pageSize, newFilter).then(flag => {
        if (flag) {
          this.pageNavigation.total = this.collectionObject.total;
          this.loading = false;
        } else {
          this.loading = false;
        }
      })
    },
    getRecord(filter) {
      let newFilter = this.collectionObject.util.getFilter(filter);
      return this.classObject.query(newFilter).then(flag => {
        if (flag) {
          return this.classObject.record;
        } else {
          return false;
        }
      })
    },
    deleteRecord(ids) {
      let _this = this;
      this.loading = true;
      return this.collectionObject.deleteByIds(ids).then(flag => {
        if (flag) {
          ids.forEach(id => {
            let index = _this.collectionObject.records.findIndex(item => item.id === id);
            if (index !== -1) {
              _this.collectionObject.records.splice(index, 1)
            }
          })
          this.loading = false;
          return true;
        } else {
          this.loading = false;
          return false;
        }
      })
    },
    handleSearch(filter) {
      this.pageNavigation.pageNumber = 1;
      this.loadPage(this.pageNavigation, filter)
    },
    handleCreate() {
      this.$set(this.addNewPanel.drawer, 'show', true)
    },
    handleReset() {
      this.pageNavigation.pageNumber = 1;
      this.loadPage(this.pageNavigation, null)
    },
    handleNewAddSubmit(data) {
      this.loading = true;
      this.classObject.add(data).then(flag => {
        if (flag) {
          this.collectionObject.records.unshift(this.classObject.record);
          this.loading = false;
          this.$set(this.addNewPanel.drawer, 'show', false)
        } else {
          this.loading = false;
        }
      })
    },
    async handleEdit(row, index) {
      this.loading = true;
      if (await this.getRecord({ type: row.type, className: row.className })) {
        this.$set(this.editPanel, 'data', this.classObject.record);
        this.$set(this.editPanel.drawer, 'show', true);
        this.loading = false;
      } else {
        this.loading = false;
      }
    },
    handleEditSubmit(data) {
      this.loading = true;
      this.classObject.setRecord(data);
      this.classObject.update().then(flag => {
        if (flag) {
          let index = this.collectionObject.records.findIndex(item => item.id === this.classObject.record.id);
          if (index !== -1) {
            this.collectionObject.records.splice(index, 1, this.classObject.record)
          }
          this.loading = false;
          this.$set(this.editPanel.drawer, 'show', false);
        } else {
          this.loading = false;
        }
      })
    },
    async handleDetail(row, index) {
      this.loading = true;
      if (await this.getRecord({ type: row.type, className: row.className })) {
        this.$set(this.readPanel, 'data', this.classObject.record);
        this.$set(this.readPanel.drawer, 'show', true);
        this.loading = false;
      } else {
        this.loading = false;
      }
    },
    handleDelete(row, index) {
      this.deleteRecord([row.id])
    },
    async hierDesign(row, index) {
      this.record = await this.getRecord({ type: row.type, className: row.className });
      if (!this.record.hier || this.record.hier.length == 0) {
        this.record.hier = [this.model.tpl()];
      };
      let data = this.record.hier[0];
      data.param = data.param || {}
      this.modelType = row.type;
      this.hierData = data;
      this.hierDrawer.show = true;
    },
    async handleDeleteMultiple(selection) {
      let ids = [];
      selection.map(item => ids.push(item.id));
      await this.deleteRecord(ids).then(flag => {
        if (flag) {
          this.$refs.table.selection = [];
        }
      });
    },
    submitHier(data) {
      console.log('submitHier', this.record);
      this.record.hier = [data];
      this.classObject.setRecord(this.record);
      this.classObject.update().then(flag => {
        if (flag) {
          let index = this.collectionObject.records.findIndex(item => item.id === this.classObject.record.id);
          if (index !== -1) {
            this.collectionObject.records.splice(index, 1, this.classObject.record)
          }
          this.hierDrawer.show = false;
        }
      })
    }
  }
}
</script>

<style scoped></style>
